package com.tc.itfarm.api.util;

import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;

import java.lang.reflect.Field;
import java.util.List;

/**
 * bean工具类 复制
 * Created by wangdongdong on 2016/8/31.
 */
public class BeanMapper {

    private static final Logger logger = LoggerFactory.getLogger(BeanMapper.class);

    private BeanMapper(){}

    /**
     * 复制对象
     * @param des
     * @param source
     */
    public static void copy(Object des, Object source) {
        BeanUtils.copyProperties(source, des);
    }

    /**
     * 复制集合指定字段
     * @param source 源集合
     * @param fieldType 字段类型
     * @param fieldName 字段名
     * @param <T>
     * @param <U>
     * @return 指定字段的集合
     */
    public static <T, U> List<T> copyPropertyToList(List<U> source, Class<T> fieldType, String fieldName) {
        Assert.notNull(fieldType);
        List<T> list = Lists.newArrayList();
        try {
            for (U u : source) {
                Field field = u.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                Object obj = field.get(u);
                if (!fieldType.equals(obj.getClass())) {
                    throw new RuntimeException("参数类型不一致!");
                }
                list.add((T)obj);
            }
        } catch (NoSuchFieldException e) {
            logger.error("no such field named" + fieldName);
            throw new RuntimeException("no such field named" + fieldName);
        } catch (IllegalAccessException e) {
            logger.error("参数类型不合法!");
            throw new RuntimeException("参数类型不合法!");
        }
        return list;
    }

}
